package com.gthncz;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ServerDemo {
    private final static int SERVER_PORT = 65500;

    public static void main(String[] agrs) {

        // 创建线程池处理 socket
        int NCPUS = Runtime.getRuntime().availableProcessors();
        ExecutorService threadPool = Executors.newFixedThreadPool(NCPUS);

        // 监听通信
        System.out.println("server listening...");
        Socket socket = null;
        try {
            ServerSocket serverSocket = new ServerSocket(SERVER_PORT);
            while (!Thread.currentThread().isInterrupted() && (socket = serverSocket.accept()) != null){
                // 直接提交给线程池
                threadPool.submit(new SocketTask(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Server terminate.");
        }
    }

    /**
     * 简单的处理 socket 通信
     * 接收数据, 并按原样返回
     */
    protected static class SocketTask implements Runnable {

        public Socket socket;

        public SocketTask(Socket socket){
            this.socket = socket;
        }

        @Override
        public void run() {
            System.out.println("============================");
            int localPort = socket.getLocalPort();
            String addr = socket.getLocalAddress().getHostAddress();
            System.out.println("addr: " + addr + " Port: " + localPort);

            InputStream is = null;
            OutputStream os = null;

            try {
                is = socket.getInputStream();
                os = socket.getOutputStream();
                StringBuilder builder = new StringBuilder();
                byte[] buffer = new byte[1024];
                int len = -1;
                while ((len = is.read(buffer)) != -1) {
                    builder.append(new String(buffer, 0, len));
                }
                socket.shutdownInput();
                String content = builder.toString();
                System.out.println("recv content: " + content);
                System.out.flush();

                os.write(content.getBytes());
                os.flush();
                socket.shutdownOutput();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (os != null) os.close();
                    if (is != null) is.close();
                    if (socket != null) socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            System.out.println("---------------\n\n");
        }
    }

}
